{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "#\n",
    "from typing import List #类型注解\n",
    "def sortOneElem(nums:List[int], begin:int, end:int, elem:int) -> int:\n",
    "    i = begin\n",
    "    j = begin\n",
    "    while(j <= end):\n",
    "        while(i <= end and nums[i] == elem): #找第一个不是elem的元素\n",
    "            i += 1\n",
    "        j = i + 1\n",
    "        while(j <= end and nums[j] != elem): #找i后面第一个是elem的元素\n",
    "            j += 1\n",
    "        if(j > end):\n",
    "            break\n",
    "        nums[i],nums[j] = nums[j], nums[i]\n",
    "        i += 1\n",
    "    return i\n",
    "        \n",
    "class Solution:\n",
    "    def sortColors(self, nums: List[int]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify nums in-place instead.\n",
    "        \"\"\"\n",
    "        l = len(nums)\n",
    "        begin = 0\n",
    "        begin = sortOneElem(nums, begin, l-1, 0)\n",
    "        begin = sortOneElem(nums, begin, l-1, 1)\n",
    "\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [],
   "source": [
    "#方法二：\n",
    "from typing import List #类型注解\n",
    "class Solution:\n",
    "    def sortColors(self, nums: List[int]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify nums in-place instead.\n",
    "        \"\"\"\n",
    "        p = 0\n",
    "        q = len(nums)-1\n",
    "        curr = 0 #注意，是0，不是1\n",
    "        while( p < q and curr <= q):\n",
    "            if(nums[curr] == 0):\n",
    "                nums[p], nums[curr] = nums[curr], nums[p]\n",
    "                p += 1\n",
    "                curr += 1\n",
    "            elif(nums[curr] == 2):\n",
    "                nums[q], nums[curr] = nums[curr], nums[q]\n",
    "                q -= 1\n",
    "            else:\n",
    "                curr += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 0, 1]\n"
     ]
    }
   ],
   "source": [
    "a = Solution()\n",
    "nums = [2,0,2,1,1,0]\n",
    "#nums = [2,1,1,1,0]\n",
    "nums =[1,0,0,2,1]\n",
    "nums = [1,0,0]\n",
    "a.sortColors(nums)\n",
    "print(nums)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
